<?php

class DispatchdetailsController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';
    public $customer;
    public $location;

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Dispatchdetails;


        if (isset($_POST)) {
            $model->attributes = $_POST;
            if ($model->save()) {
                echo json_encode(array(
                    'success' => true,
                    'msg' => "Dispatch No. {$model->dispatch} has been created."
                ));
            } else {
                echo json_encode(array(
                    'success' => false,
                    'errors' => $model->getErrors()
                ));
            }
        }
    }


    public function actionUpdateMail($dispatch)
    {
        $tracker = Tracker::model()->find('dispatchno=:dispatchno', array(
            'dispatchno' => $dispatch
        ));
        if (empty($tracker)) {
            $tracker = new Tracker();
        }
        if ($_POST['status']) {
            $tracker->email = $_POST['email'];
            $tracker->dispatchno = $dispatch;
            $tracker->save();
        } else {
            if (!$tracker->isNewRecord) {
                $tracker->delete();
            }
        }


    }


    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($dispatch)
    {
        $model = $this->loadModel($dispatch);
        if($model->custno!=Yii::app()->user->custno)
            throw new CHttpException(404, 'The requested page does not exist.');
        $this->loadObject($model->custno, $model->locno);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Dispatchdetails'])) {
            $model->attributes = $_POST['Dispatchdetails'];
            if ($model->save()) {
            }

        }
        outputJsByList(Dispatchequipment::model()->getEquipmentList($dispatch), 'equipment', true);
        $this->render('update', array(
            'model' => $model,
            'location' => $this->location,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($dispatch)
    {

        // we only allow deletion via POST request
        $model = $this->loadModel($dispatch);
        $model->delete();

    }

    /**
     * Lists all models.
     */
    public function actionIndex($locno = -1, $type = -1, $complete = -1)
    {

        $custno = Yii::app()->user->custno;
        $this->location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'locno' => $locno,
            'custno' => $custno,
        ));
        $this->customer = Customers::model()->find('custno=:custno', array(
            'custno' => $custno
        ));
        outputJsByList(Dispatchdetails::model()->getDepartmentList(), 'department');
        outputJsByList(Dispatchdetails::model()->getPriorityList(), 'priority');

        outputJsByList(JobsClass::getList(), 'job');
        Yii::app()->clientScript->registerScript('type', "var type='$type';", CClientScript::POS_HEAD);
        Yii::app()->clientScript->registerScript('complete', "var complete=$complete;", CClientScript::POS_HEAD);
        $caller = getUserRealname(Yii::app()->user->name);
        Yii::app()->clientScript->registerScript('caller', "var caller='$caller';", CClientScript::POS_HEAD);
        $this->render('index', array(
            'customer' => $this->customer,
            'location' => $this->location,
            'type' => $type,
            'complete' => $complete
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Dispatchdetails::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function loadObject($custno, $locno)
    {
        $this->location = Locations::model()->find('locno=:locno and custno=:custno', array(
            'locno' => $locno,
            'custno' => $custno
        ));
        $this->customer = Customers::model()->find('custno=:custno', array(
            'custno' => $custno
        ));
        if ($this->location === null || $this->customer === null)
            throw new CHttpException(404, 'The requested page does not exist.');
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'dispatchdetails-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

   public function actionList($custno, $locno,$query=null, $page = 0, $sort = NULL, $type = -1, $complete = -1,$status=null)
    {
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $criteria = new CDbCriteria();
        if($query!=NULL){
            $criteria->compare('dispatch', $query, true, 'or');
            $criteria->compare('locno', $query, true, 'or');
            $criteria->compare('receiveddate', $query, true, 'or');
            $criteria->compare('receivedtime', $query, true, 'or');
        }
        $criteria->addColumnCondition(array('custno'=>$custno));
        $criteria->addCondition("department !='CORP - Internal Dispatches'");
        if ($locno != -1) {
            $criteria->addColumnCondition(array('locno' => $locno));
        }
        $criteria->order = isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL;
        if ($type != -1) {
            $criteria->addColumnCondition(array('department' => $type));
        }
        if ($complete == 0) {
            $criteria->addCondition('t.complete is  null');
        }
        if ($complete == 1) {
            $criteria->addCondition('t.complete is not null');
        }



        $data = new CActiveDataProvider('Dispatchdetails', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20,
                'currentPage' => $page
            )
        ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {

                $rs['data'][$i] = $item->getAttributes();
                if ($item->lastestTech != NULL) {
                    if ($item->lastestTech->employee != NULL) {
                        $rs['data'][$i]['technician'] = $item->lastestTech->employee->firstname . ' ' . $item->lastestTech->employee->lastname;
                    }
                    $rs['data'][$i]['techStatus'] = $item->lastestTech->status;
                }
                $rs['data'][$i]['department'] = $item->department;
                if ($locno = -1) {
                    $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
                        'custno' => $custno,
                        'locno' => $item->locno,
                    ));
                    if (!empty($location)) {
                        $rs['data'][$i]['custAdd'] = $location->add1;
                        $rs['data'][$i]['custCity'] = "$location->city $location->state $location->zip";
                    } else {
                        $rs['data'][$i]['locno'] = 'Not set';
                    }
                }
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

}

